package com.backstage.service.impl;

import com.backstage.common.annotation.transaction.Commit;
import com.backstage.common.annotation.transaction.ReadOnly;
import com.backstage.common.page.Page;
import com.backstage.dao.MenuDao;
import com.backstage.dao.RoleDao;
import com.backstage.entity.Menu;
import com.backstage.entity.Role;
import com.backstage.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project authority
 * @Package com.backstage.service.impl
 * @Data 2017/7/27下午 3:49.
 * @Aurhor 阮雪峰
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;

    @ReadOnly
    @Override
    public void roleByPage(Page<Role> page, Role role) {
        int totalCol = roleDao.getTotalColumn(page, role);
        List<Role> list = roleDao.getList(page, role);

        page.setTotal(totalCol);
        page.setRows(list);
    }

    @Commit
    @Override
    public void add(Role role) {
        roleDao.add(role);
    }

    @Commit
    @Override
    public void edit(Role role) {
        roleDao.edit(role);
    }

    @Commit
    @Override
    public void delete(ArrayList<Role> roles) {
        roleDao.deleteBach(roles);
        roleDao.deleteRolesMenus(roles);
        roleDao.deleteUsersRoles(roles);
    }

    @Commit
    @Override
    public void allotPower(Role role) {
        roleDao.deleteRoleMenu(role);
        roleDao.allotPower(role);
    }

    @ReadOnly
    @Override
    public Role queryRoleById(Role role) {
        return roleDao.getObjById(role);
    }

    @ReadOnly
    @Override
    public Map<String, List<Menu>> getRoleMenu(Role role) {
        Map<String, List<Menu>> map = new HashMap<>();
        List<Menu> roleMenu = roleDao.getRoleMenu(role);
        List<Menu> allMenu = menuDao.getAllMenu();

        List<Menu> list = new ArrayList<>();
        for (Menu menu : allMenu) {
            if(menu.getType() == 1){
                findChildren(allMenu, menu);
                list.add(menu);
            }else if(menu.getType() == 2){
                findChildren(allMenu, menu);
            }
        }

        map.put("allMenu", list);
        map.put("roleMenu", roleMenu);
        return map;
    }

    private void findChildren(List<Menu> all, Menu parent){
        for (Menu menu : all) {
            if(parent.getMenu_id() == menu.getSuper_id()){
                parent.getChildren().add(menu);
            }
        }
    }
}
